package com.fbms.module.system.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbms.common.utils.CommonBeanUtils;
import com.fbms.common.utils.StreamKit;
import com.fbms.module.system.bean.dto.SysMenuDTO;
import com.fbms.module.system.bean.entity.SysMenu;
import com.fbms.module.system.dao.SysMenuMapper;
import com.fbms.module.system.service.ISysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类描述：TODO
 *
 * @ClassName SysMenuServiceImpl
 * @Author HappyBoy
 * @Date 2023-04-03 10:34
 **/
@RequiredArgsConstructor
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    /**
     * 菜单Mapper
     */
    private final SysMenuMapper menuMapper;

    /**
     * 根据角色Id查询菜单信息
     * @param roleId 角色Id
     * @return 菜单列表
     */
    @Override
    public List<SysMenuDTO> getMenuListByRoleId(String roleId) {
        // 根据角色ID查询关系表 然后 查询菜单
        List<SysMenuDTO> sysMenus = menuMapper.selectMenuListByRoleId(roleId);

        // 转换成树级结构
        return listToTreeList(sysMenus, "0", true);
    }

    /**
     * 查询菜单列表
     * @return 菜单列表
     */
    @Override
    public List<SysMenuDTO> getMenuList() {
        List<SysMenu> menus = list();
        List<SysMenuDTO> menuDTOList = StreamKit.convertList(menus, entity -> CommonBeanUtils.doToDto(entity, SysMenuDTO.class));
        return listToTreeList(menuDTOList, "0", true);
    }


    /**
     * 转成菜单树
     * @param sysMenus 系统菜单
     * @param rootNode 根节点
     * @param isSort 是否排序
     * @return 菜单树
     */
    private List<SysMenuDTO> listToTreeList(List<SysMenuDTO> sysMenus, String rootNode, boolean isSort) {
        List<SysMenuDTO> rootMenu = getMenus(sysMenus, rootNode, isSort);
        for(SysMenuDTO dto : rootMenu){
            String id = dto.getId();
            List<SysMenuDTO> childrenMenu = getMenus(sysMenus, id, isSort);

            dto.setChildren(childrenMenu);
        }
        return rootMenu;
    }

    private List<SysMenuDTO> getMenus(List<SysMenuDTO> menus, String node, boolean isSort) {
        List<SysMenuDTO> res = menus.stream().filter(item -> node.equals(item.getParentId())).collect(Collectors.toList());
        if(isSort){
            res.sort(new Comparator<SysMenuDTO>() {
                @Override
                public int compare(SysMenuDTO o1, SysMenuDTO o2) {
                    return o1.getSort() - o2.getSort();
                }
            });
        }
        return res;
    }




}
